import serial
import threading
import time


def serial_test():
    # 假设你有一对虚拟串口 COM1 和 COM2
    sender = serial.Serial('COM1', 9600, timeout=1)
    receiver = serial.Serial('COM2', 9600, timeout=1)

    def receive_thread():
        while True:
            if receiver.in_waiting > 0:
                data = receiver.readline().decode().strip()
                print(f"接收端收到: {data}")

    # 启动接收线程
    thread = threading.Thread(target=receive_thread, daemon=True)
    thread.start()

    try:
        counter = 0
        while True:
            # 发送测试数据
            message = f"测试数据 {counter}\n"
            sender.write(message.encode())
            print(f"发送端发送: {message.strip()}")

            counter += 1
            time.sleep(2)

    except KeyboardInterrupt:
        sender.close()
        receiver.close()
        print("测试结束")


if __name__ == "__main__":
    serial_test()
